package main

import (
	"strings"

	_ "github.com/go-sql-driver/mysql"

	"github.com/topfreegames/pitaya/v2"
	"github.com/topfreegames/pitaya/v2/component"
	"github.com/topfreegames/pitaya/v2/config"
	"github.com/topfreegames/pitaya/v2/groups"
	"github.com/topfreegames/pitaya/v2/modules"
	"github.com/topfreegames/pitaya/v2/serialize/protobuf"

	"webgame/internal/constants"
	"webgame/internal/dao"
	hallManager "webgame/internal/manager/hall"
	"webgame/internal/services/hall"
	pkgconfig "webgame/pkg/config"
	"webgame/pkg/global"
)

// var app pitaya.Pitaya

func main() {

	setting, vipErr := pkgconfig.NewServerConfig("hall.yaml")

	if vipErr != nil {
		panic(vipErr)
	}

	config := config.NewDefaultPitayaConfig()
	builder := pitaya.NewDefaultBuilder(false, "hall", pitaya.Cluster, map[string]string{}, *config)

	builder.Serializer = protobuf.NewSerializer()
	builder.Groups = groups.NewMemoryGroupService(builder.Config.Groups.Memory)

	//创建pitaya实例
	global.ServerApp = builder.Build()

	defer global.ServerApp.Shutdown()

	//注册数据库
	dataSource := &modules.DataSourceConfig{
		DSN:         setting.MySQL.Dsn,
		MaxIdle:     setting.MySQL.MaxIdleConns,
		MaxOpen:     setting.MySQL.MaxOpenConns,
		MaxLiftTime: setting.MySQL.MaxLifeTime,
	}
	ds, dbErr := modules.NewDatabaseStorage(dataSource)
	if dbErr != nil {
		panic(dbErr)
	}
	global.ServerApp.RegisterModule(ds, "databaseStorage")

	//注册Redis
	redisSource := &modules.RedisConfig{
		Addr:     setting.Redis.Addr,
		Password: setting.Redis.Password,
		DB:       setting.Redis.DB,
	}
	rs := modules.NewRedisStorage(redisSource)
	global.ServerApp.RegisterModule(rs, "redisStorage")

	//注册Dao
	global.ServerApp.RegisterDao(dao.NewUserDataDao())

	//注入handler
	loginHandler := hall.NewLoginHandler()
	global.ServerApp.Register(loginHandler,
		component.WithName("login"),
		component.WithNameFunc(strings.ToLower),
	)
	global.ServerApp.RegisterRemote(loginHandler,
		component.WithName("login"),
		component.WithNameFunc(strings.ToLower),
	)

	//注册管理器
	loginM := hallManager.NewLoginManager()
	global.ServerApp.RegisterManger(loginM)
	// loginM.TestDao()

	//注册线程
	loginThread := hallManager.NewLoginThread()
	global.ServerApp.RegisterThread(loginThread,
		component.WithName(constants.LoginThread),
		component.WithNameFunc(strings.ToLower),
	)

	//启动实例
	global.ServerApp.Start()

}
